/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.tk.remotecontrol

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Service for managing connection and data communication with a GATT server hosted on a
 * given Bluetooth LE device.
 */
class TransferSocketService : Service() {
    private var serverSocket: ServerSocket? = null
    private var commandServerIp: String? = null
    private var receiveVideoListener: ReceiveVideoListener? = null
    private var executorService: ExecutorService = Executors.newSingleThreadExecutor()

    fun receiveVideoListenerInitialize() {
        try { //开启服务、指定端口号
            if(serverSocket == null){
                serverSocket = ServerSocket(8819)
                receiveVideoListener = ReceiveVideoListener(this)
                receiveVideoListener?.start()
            }
        } catch (e: IOException) {
            e.printStackTrace()
            return
        }
    }

    fun setCommandServerIp(ip: String) {
        commandServerIp = ip
    }

    fun transferCommand(data: String) {
        executorService.execute(TransferCommandRunnable(data, this))
        Log.d("log", "TransferVideo: ")
    }

    private fun broadcastString(action: String, data: String) {
        val intent = Intent(action)
        intent.putExtra("data", data)
        sendBroadcast(intent)
    }

    private fun broadcastBytes(action: String, data: ByteArray) {
        val intent = Intent(action)
        intent.putExtra("data", data)
        sendBroadcast(intent)
    }

    private val binder: IBinder = LocalBinder()

    fun close() {
        serverSocket?.close()
        receiveVideoListener?.interrupt()
    }

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    override fun onUnbind(intent: Intent): Boolean {
        close()
        return super.onUnbind(intent)
    }

    internal inner class LocalBinder : Binder(), ITransferSocketServiceBinder {
        override fun getService(): TransferSocketService {
            return this@TransferSocketService
        }
    }

    class ReceiveVideoListener(var service: TransferSocketService) : Thread() {
        private val serverSocket : ServerSocket = service.serverSocket!!
        override fun run() {
            val buffer = ByteArray(1024)
            var len = 0
            while (true) {
                try {
                    val socket = serverSocket.accept()
                    //Log.d("lxk", "run:tcp 接收图片数据 ");
                    //Log.d("lxk", "run:tcp 接收图片数据 ");
                    val `is` = socket.getInputStream()
                    //用于写到图片
                    //用于写到图片
                    val outStream = ByteArrayOutputStream()
                    while (`is`.read(buffer).also { len = it } != -1) {
                        outStream.write(buffer, 0, len)
                    }
                    `is`.close()
                    val bytes = outStream.toByteArray()
                    //mBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    service.broadcastBytes(VIDEOPICTURE, bytes)

                    outStream.flush()
                    outStream.close()

                    socket.close() // 关闭socket

                } catch (e: Exception) {
                    Log.d("出错", "SocketListener")
                    return
                }
                //执行操作
                if (this.isInterrupted()){
                    break;
                }
            }
        }

    }

    internal class TransferCommandRunnable(var data: String, var service: TransferSocketService) : Runnable {
        override fun run() {
            if(service.commandServerIp != null){
                try {
                    val socket = Socket()
                    socket.connect(InetSocketAddress(service.commandServerIp, 8820), 5000)
                    val os = socket.getOutputStream()
                    //写入要发送给服务器的数据
                    os.write(data.toByteArray())
                    os.flush()
                    socket.shutdownOutput()
                    os.close()
                    socket.close()
                    Log.d("log", "TransferVideoThreadOk: ")
                    service.broadcastString(TransferSocketService.SENTOK, "")
                } catch (e: Exception) {
                    Log.d("log", "TransferVideoThreadException: ")
                    service.broadcastString(TransferSocketService.SENTERROR, "")
                    e.printStackTrace()
                }
            }
        }
    }
    companion object {
        const val VIDEOPICTURE : String = "com.tk.remotecontrol.VideoPicture"
        const val SENTERROR : String = "com.tk.remotecontrol.SentError"
        const val SENTOK : String = "com.tk.remotecontrol.SentOk"
    }

}



